<script lang="ts" setup>
import type { OrderItem, SubBillItem } from '@/types/api/order'
import type { Ref } from 'vue'

import { orderApi } from '@/request/api'
import { useAppConfig } from '@/stores'
import { useConsole, useDayjs, useDayjsFormat, useJsonDeepParse, useModal, useNav, useRouteGuard } from '@/utils'
import { onLoad, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty } from 'lodash-es'
import { ref } from 'vue'
import { object as zobject, string as zstring } from 'zod'

type ListItem = OrderItem['productOrderRecordVoList'][0] & {
  /** 分期账单 */
  _sub_bill?: SubBillItem[]
  /** 当期开始日 */
  _expiretime: string
  /** 当期结束日 */
  _duetime: string
  /** “提前”标识 */
  _ahead: boolean
}

const appConfig = useAppConfig()

const oid = ref() as Ref<number>
const keyItem = ref() as Ref<ListItem>
const leaseTerm = ref(0)
const dataList = ref<ListItem[]>([])

onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
    msg: zstring().transform(decodeURIComponent).optional(),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }
  oid.value = zparse.data.oid
  await getDetail()
  if (!isEmpty(zparse.data.msg)) {
    if (dataList.value[0].payment === 0) {
      useModal({
        title: '提示',
        content: zparse.data.msg,
        showCancel: false,
        confirmText: '好的',
      })
    }
  }
})

onShow(async () => {
  if (!isEmpty(dataList.value)) {
    await getDetail()
  }
})

onPullDownRefresh(async () => {
  await getDetail()
  uni.stopPullDownRefresh()
})

async function getDetail() {
  // 订单详情
  const [err1, res1] = await to(orderApi.detail(oid.value))
  if (err1) {
    return
  }

  const data1 = useJsonDeepParse<OrderItem>(JSON.stringify(res1))

  // 各子订单数据
  const [err2, res2] = await to(orderApi.recordPeriodList(data1.productOrderRecordVoList.map(x => x.id)))
  if (err2) {
    return
  }

  leaseTerm.value = data1.leaseTerm
  dataList.value = data1.productOrderRecordVoList.map((x) => {
    const data = { ...x } as Record<string, any>

    data._expiretime = useDayjsFormat(data.expiretime, 'DD')
    data._duetime = useDayjsFormat(data.duetime, 'DD')
    if (x.id in res2) {
      data._sub_bill = res2[data.id]
    }
    data._ahead = useDayjs(data.expiretime).isAfter(useDayjs(), 'D')

    return data as ListItem
  })
}

function handleNavSubBill(item: ListItem) {
  useNav('/order/bill/sub-list', {
    oid: oid.value,
    bid: item.id,
  })
}

function handleConsole(item: ListItem) {
  useConsole?.log(item)
}
</script>

<template>
  <view
    v-if="!isEmpty(dataList)"
    class="px-30px pt-20px safe-pb-20px"
  >
    <template
      v-for="(item, i) in dataList"
      :key="i"
    >
      <view
        class="rd-16px bg-white"
        :class="{ 'mt-10px': i !== 0 }"
      >
        <!--  -->
        <view
          class="px-10px pt-10px"
          @longpress="handleConsole(item)"
        >
          <view
            class="flex rd-full px-20px text-24px"
            :class="['bg-theme-primary/10', 'bg-#F4F5F9', 'bg-#F4F5F9'][item.payment]"
          >
            <view class="text-#3 lh-50px">第&thinsp;{{ item.period }}&thinsp;期</view>
            <view class="ml-a text-#6 lh-50px">租期：{{ item._expiretime }}&thinsp;-&thinsp;{{ item._duetime }} ({{
              item.period }}/{{ leaseTerm }})</view>
          </view>
        </view>
        <!--  -->
        <view class="flex flex-col items-center pb-50px pt-60px">
          <view class="text-36px text-#3">本期还款 ￥{{ (item.price / 100).toFixed(2) }}</view>
          <view
            v-if="item.payment === 1 && !isEmpty(item._sub_bill)"
            class="mt-20px flex items-center"
            @click="handleNavSubBill(item)"
          >
            <view class="text-24px text-#6a">分期明细</view>
            <view class="i-ri:arrow-right-wide-line text-24px"></view>
          </view>
        </view>
        <!--  -->
        <view class="flex items-center justify-between px-22px pb-20px">
          <!-- payment: 0 未付款  1 已完成  2 半完成 -->
          <template v-if="item.payment !== 1">
            <!--  -->
            <view class="flex flex-col items-start">
              <view
                v-if="!appConfig.hidePayBtn"
                class="relative pb-5px"
              >
                <view class="flex-start flex b-2px b-#e4 rd-full b-solid">
                  <view class="h-30px w-30px flex">
                    <view class="text-theme-primary i-ri:error-warning-line m-a text-18px"></view>
                  </view>
                  <view class="text-theme-primary py-6px pr-10px text-18px">亲记得按时还款以免忘记</view>
                </view>
                <view
                  class="absolute bottom-0 left-35px h-10px w-10px rotate-45deg b-2px b-#e4 b-solid b-l-none b-t-none bg-white"
                ></view>
              </view>
              <view class="mt-5px flex text-24px">
                <view class="text-#6a">交租日期：</view>
                <view class="text-#3">{{ item._expiretime }}&thinsp;之前</view>
              </view>
            </view>
            <!--  -->
            <view class="flex">
              <view
                v-if="!isEmpty(item._sub_bill)"
                class="btn-primary-black w-160px text-26px lh-60px"
                @click="handleNavSubBill(item)"
              >分期明细</view>
              <template v-else>
                <cm-pay-btn
                  :id="oid"
                  pay-status="3"
                  :oid="item.id"
                  @pay-order="getDetail"
                >
                  <template #name>
                    <view
                      v-if="!appConfig.hidePayBtn"
                      class="btn-primary-black w-160px text-26px lh-60px"
                    >{{ item._ahead ? '提前' : '立即' }}交租
                    </view>
                  </template>
                </cm-pay-btn>
              </template>
            </view>
          </template>
          <template v-else>
            <view class="flex text-24px">
              <view class="text-#6a">交租日期：</view>
              <view class="text-#3">{{ item._duetime }}</view>
            </view>
            <view class="flex items-center">
              <view class="i-ri:checkbox-circle-fill text-30px text-#60CC84"></view>
              <view class="ml-5px text-24px text-#6">已交租金</view>
            </view>
          </template>
        </view>
      </view>
    </template>
  </view>
  <view
    v-else
    class="px-30px py-20px"
  >
    <view class="h-300px rd-16px bg-white"></view>
    <view class="mt-10px h-300px rd-16px bg-white"></view>
    <view class="mt-10px h-300px rd-16px from-white to-transparent bg-gradient-to-b"></view>
  </view>
</template>

<style lang="less" scoped></style>
